﻿$currentScriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path

# 定义配置文件路径
$migratorConfigFilePath = Join-Path -Path $currentScriptPath -ChildPath "migrator.json"

# 检查配置文件是否存在
if (-Not (Test-Path $migratorConfigFilePath)) {
    # 创建新的配置对象，仅包含迁移相关的配置
    $config = @{
        MigrationDownloadUrl = ""
        MigrationDllName = ""
    }

    # 手动输入迁移包下载地址
    do {
        $migrationDownloadUrl = Read-Host "请输入迁移包下载地址"
    } while ([string]::IsNullOrWhiteSpace($migrationDownloadUrl))

    # 提取 MigrationDllName 默认值
    $fileName = [System.IO.Path]::GetFileNameWithoutExtension($migrationDownloadUrl)
    if ($fileName.EndsWith(".latest")) {
        $fileName = $fileName -replace "\.latest", ""
    }
    $defaultMigrationDllName = "$fileName.dll"

    $migrationDllName = Read-Host "请输入迁移执行dll名称 (默认: $defaultMigrationDllName)" -Default $defaultMigrationDllName
    if ([string]::IsNullOrWhiteSpace($migrationDllName)) {
        $migrationDllName = $defaultMigrationDllName
    }

    # 更新配置对象
    $config.MigrationDownloadUrl = $migrationDownloadUrl
    $config.MigrationDllName = $migrationDllName

    # 将配置写入JSON文件，使用UTF-8 BOM编码
    if ($PSVersionTable.PSVersion.Major -ge 6) {
        ConvertTo-Json -InputObject $config | Out-File -FilePath $migratorConfigFilePath -Encoding utf8BOM
    } else {
        $jsonContent = ConvertTo-Json -InputObject $config
        $bom = [byte[]]@(0xEF, 0xBB, 0xBF)
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($jsonContent)
        [System.IO.File]::WriteAllBytes($migratorConfigFilePath, $bom + $bytes)
    }
} else {
    # 读取配置文件
    $config = Get-Content -Path $migratorConfigFilePath | ConvertFrom-Json
}

$migratorDirectory = Join-Path -Path $currentScriptPath -ChildPath "migrator"
$zipFileName = [System.IO.Path]::GetFileName($config.MigrationDownloadUrl)
$zipFilePath = Join-Path -Path $currentScriptPath -ChildPath $zipFileName

# 如果不存在 migrator 目录，则创建目录
if (-Not (Test-Path $migratorDirectory)) {
    New-Item -ItemType Directory -Path $migratorDirectory | Out-Null
}

# 检查是否有本地zip包，否则远程下载并解压迁移包
if (Test-Path $zipFilePath) {
    Write-Output "找到本地迁移包，正在解压..."
    Expand-Archive -Path $zipFilePath -DestinationPath $migratorDirectory -Force
    Write-Output "迁移包已成功解压到 $migratorDirectory"
} else {
    Write-Output "migrator 目录不存在，正在下载迁移包..."
    Invoke-WebRequest -Uri $config.MigrationDownloadUrl -OutFile $zipFilePath
    Expand-Archive -Path $zipFilePath -DestinationPath $migratorDirectory -Force
    Write-Output "迁移包已成功解压到 $migratorDirectory"
}

# 切换到解压的目录
Set-Location -Path $migratorDirectory

# 使用 dotnet 运行迁移
$migrationDllPath = Join-Path -Path $migratorDirectory -ChildPath $config.MigrationDllName

Write-Output "正在执行数据库迁移..."
& dotnet $migrationDllPath

if ($LASTEXITCODE -eq 0) {
    Write-Output "数据库迁移成功。"
} else {
    Write-Output "数据库迁移失败。"
}

# 返回原始工作目录
Set-Location -Path $currentScriptPath

# 保持脚本窗口打开
Read-Host "按 Enter 键退出..."



